<?php
/**
 * lemocms
 * ============================================================================
 * 版权所有 2018-2027 lemocms，并保留所有权利。
 * 网站地址: https://www.lemocms.com
 * ----------------------------------------------------------------------------
 * 采用最新Thinkphp6实现
 * ============================================================================
 * Author: yuege
 * Date: 2019/8/2
 */

namespace app\admin\controller;

use app\admin\controller\ucenter\User;
use app\admin\model\Admin;
use app\common\controller\Backend;
use app\common\model\StudentTopic;
use app\common\traits\Curd;
use think\facade\Request;
use think\facade\View;
use think\facade\Db;
use app\common\model\Schedule as ScheduleModel;
use app\common\model\Topic;
use app\common\model\Grade;

// 环节列表
class Schedule extends Backend
{
    use Curd;

    protected $user_info;

    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->modelClass = new ScheduleModel();
        $this->user_info = session('admin');
    }

    public function index()
    {
        if ($this->request->isPost()) {
            $keys = $this->request->post('keys', '', 'trim');

            $where = [];
            $where['student_id'] = $this->user_info['id'];
            if ($keys != '') {
                $where['title'] = ['like', '%' . $keys . '%'];
            }

            $page = $this->request->post('page');
            $limit = $this->request->post('limit');
            $tol = ($page - 1) * $limit;

            $schedule = ScheduleModel::where($where)->limit($tol, $limit)->select();
            $count = ScheduleModel::where($where)->count();

            if (!$schedule) error();
            success($schedule, $count);
        }

        //$topic_id = StudentTopic::where(['student_id' => $this->user_info['id']])->value('topic_id');
        //$topic = Topic::where(['id' => $topic_id])->find();
        $grade = Grade::where(['id' => $this->user_info['quiz3']])->value('topic_id');
        $topic = Topic::where(['id' => $grade])->find();
        $view = [
            'topic' => $topic,
            'user' => $this->user_info
        ];

        return view('', $view);
    }

    /**
     * 编辑
     * 作者：杨聪
     * 时间：2021/3/11 12:10
     */
    public function edit($id)
    {
        $list = $this->modelClass->find($id);
        if (empty($list)) $this->error('data is not exist');
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $post['file'] = $post['upfile'];
            unset($post['upfile']);
            $rule = [];
            $this->validate($post, $rule);
            try {
                $save = $list->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功', url('index')) : $this->error('保存失败');
        }

        $view = [
            'info' => $list,
            'title' => '编辑'
        ];

        return view('', $view);
    }

    /**
     * 封装下载
     * 作者：杨聪
     * 时间：2021/3/17 12:36
     */
    public function head_upload($file_name, $id)
    {

        $file_name = iconv("utf-8", "gbk//IGNORE", $file_name);;  //中文表名转码
        $file_dir = $_SERVER['DOCUMENT_ROOT'];        //下载文件存放目录
        if (!file_exists($file_dir . $file_name)) {
            header('HTTP/1.1 404 NOT FOUND');
        } else {
            //以只读和二进制模式打开文件
            $file = fopen($file_dir . $file_name, "rb");

            $sch = ScheduleModel::where(['id' => $id])->find();
            $user = Admin::where(['id' => $sch['student_id']])->find();

            $postfix = trim(strrchr($file_name, '.'),'');

            //告诉浏览器这是一个文件流格式的文件
            Header("Content-type: application/octet-stream");
            //请求范围的度量单位
            Header("Accept-Ranges: bytes");
            //Content-Length是指定包含于请求或响应中数据的字节长度
            Header("Accept-Length: " . filesize($file_dir . $file_name));
            //用来告诉浏览器，文件是可以当做附件被下载，下载后的文件名称为$file_name该变量的值。
            Header("Content-Disposition: attachment; filename=" . $user['username'].'_'. $sch['title']. $postfix);

            //读取文件内容并直接输出到浏览器
            echo fread($file, filesize($file_dir . $file_name));
            fclose($file);
            exit ();
        }

    }


}